//
//  CommentViewController.swift
//  GitOSC-Swift
//
//  Created by 李萍 on 16/3/11.
//  Copyright © 2016年 李萍. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON

class CommentViewController: UITableViewController, UIAlertViewDelegate {
    var nameSpace: String!
    var projectID: Int!
    var commitID: String!
    var comments: [GTComment] = []
    
    var projectCell: ProjectCell!
    var sendCommenFiled: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "评论"
        
        self.tableView.registerNib(UINib(nibName: "ProjectCell", bundle: nil), forCellReuseIdentifier: "projectCell")
        projectCell = self.tableView.dequeueReusableCellWithIdentifier("projectCell") as! ProjectCell
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "发表", style: UIBarButtonItemStyle.Plain, target: self, action: "sendComment")
        
        self.fetchForCommitComment()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if comments.count > 0 {
            return comments.count
        }
        return 1
    }

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if comments.count > 0 {
            let comment = comments[indexPath.row]
            
            projectCell!.contentLabel.text = comment.note
            let height = projectCell.contentLabel.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
            
            return 75 + height
        }
        return 40
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        if comments.count > indexPath.row {
            let projectCell = tableView.dequeueReusableCellWithIdentifier("projectCell", forIndexPath: indexPath) as? ProjectCell
            let comment = comments[indexPath.row]
            projectCell?.getProjectComment(comment)
            
            return projectCell!
            
        } else {
            let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
            cell.textLabel?.textAlignment = NSTextAlignment.Center
            cell.textLabel?.text = "暂无评论"
            
            return cell
        }
        
    }
    
    func fetchForCommitComment() {
        let userinfos = UserInfos()
        let private_token = userinfos.getprivateToken()
        
        let strUrl = "https://git.oschina.net/api/v3/projects/\(nameSpace)/repository/commits/\(commitID)/comment?projectid=\(projectID)private_token=\(private_token)"
        
        Alamofire.Manager.sharedInstance.request(Method.GET, strUrl).responseJSON { response in
            if let results = response.result.value {
                
                let jsonArray = JSON(results).array!
                if jsonArray.count > 0 {
                    for i in 0 ..< jsonArray.count {
                        
                        let comment = GTComment(json: jsonArray[i])
                        self.comments.append(comment)
                    }
                    
                    self.tableView.reloadData()
                }
            
            }
        }
    }
    
    //发表评论
    func sendComment() {
        let actionSheetController: UIAlertController = UIAlertController(title: "发表评论", message: "", preferredStyle: .Alert)

        actionSheetController.addTextFieldWithConfigurationHandler { commentFiled -> Void in
            commentFiled.placeholder = "请填写您的评论"
        }
        let cancelAction: UIAlertAction = UIAlertAction(title: "取消", style: .Cancel) { action -> Void in }
        let nextAction: UIAlertAction = UIAlertAction(title: "发表", style: .Default) { action -> Void in
            let send = actionSheetController.textFields!.first! as UITextField
            self.postToComment(send.text!)
        }
        
        actionSheetController.addAction(cancelAction)
        actionSheetController.addAction(nextAction)
        
        self.presentViewController(actionSheetController, animated: true, completion: nil)
    }
    
    func postToComment(newCommentString: String) {
        let userinfos = UserInfos()
        let private_token = userinfos.getprivateToken()
        
        let strUrl = "https://git.oschina.net/api/v3/projects/\(projectID)/repository/commits/\(commitID)/comment?note=\(newCommentString)&private_token=\(private_token)"
        
        Alamofire.Manager.sharedInstance.request(Method.GET, strUrl).responseJSON { response in
            if let results = response.result.value {
                let json = JSON(rawValue: results)!
                
                let comment = GTComment(json: json)
                self.comments.append(comment)
                
                self.tableView.reloadData()
            }
        }
    }

}
